package com.game.service.app;

import com.game.service.app.get_score.JsonBean;
import com.game.service.db.UserScoreDaoImpl;
import com.game.service.socket.FileUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.List;

import static com.game.service.app.Score.doPostForm;
import static com.game.service.app.Utils.LogDate;
import static com.game.service.define.RoomConfig.*;

public class PostJsonDeal {

    static PostJsonDeal instance;
    public static final String POST_TYPE_PLAYING = "游玩记录";

    private ISendListener mISendListener;

    public void addListener(ISendListener mISendListener) {
        this.mISendListener = mISendListener;
    }

    public static int index = 0;

    public void post(String json, String url, String desc) {
        PostJson postJson = new PostJson();
        long time = System.currentTimeMillis();
        postJson.setPid(time + "_" + (++index));
        postJson.setGameid(GAME_ID);
        postJson.setPostJson(json);
        postJson.setPostResult(0);
        postJson.setPostUrl(url);
        postJson.setJsonDesc(desc);
        postJson.setAddCurrentTimeMillis(time);
        UserScoreDaoImpl.getInstance().addLog(postJson);//添加到数据库
        postAppServer(postJson);//发送给App总服务器
        FileUtils.writeTxtToFile("数据发送,本次发送的数据:" + postJson, LogDate(), LOG_NAME_POST_JSON);//添加到日志
    }

    private void postAppServer(PostJson json) {

        String result = doPostForm(json.getPostUrl(), json.getPostJson());
        String log = "返回=" + result;
        FileUtils.writeTxtToFile(log, LogDate(), LOG_NAME_FAIL_JSON);
        if (result.isEmpty()) {
            return;
        }
        Type type0 = new TypeToken<JsonBean>() {
        }.getType();
        JsonBean bean = new Gson().fromJson(result, type0);
        if (bean != null && bean.code == 0) {
            UserScoreDaoImpl.getInstance().updateLog(json.getPid());
            if (mISendListener != null) {
                mISendListener.sendSuccess();//发送成功
            }
            FileUtils.writeTxtToFile("数据发送,发送成功:" + json, LogDate(), LOG_NAME_POST_JSON);

        }

    }


    public interface ISendListener {
        void sendSuccess();

        void error(String e);
    }

}
